package com.hksj.Intelligentmanagement.mqtt.listener;

import com.hksj.Intelligentmanagement.entity.CallTaskOrderEntity;
import com.hksj.Intelligentmanagement.mqtt.annotation.MqttSubscription;
import com.hksj.Intelligentmanagement.mqtt.config.MqttConfig;
import com.hksj.Intelligentmanagement.mqtt.constant.Constant;
import com.hksj.Intelligentmanagement.mqtt.constant.TopicConstant;
import com.hksj.Intelligentmanagement.service.CallDeviceScreenService;
import com.hksj.Intelligentmanagement.service.CallTaskOrderService;
import com.hksj.Intelligentmanagement.vo.CallDeviceScreenVo;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@MqttSubscription(topics = {TopicConstant.client_create_order},targetClient = MqttConfig.SECOND_CLIENT)
public class CreateOrderListener extends ListenerMqttClientSupport implements MqttListener{
    @Autowired
    private CallDeviceScreenService screenService;

    @Autowired
    private CallTaskOrderService taskOrderService;

    @Autowired
    private Redisson redisson;

    @Override
    public void receive(String topic, MqttMessage mqttMessage) {
        getMqttClient().getCallBackAdapter().getExecutor().execute(() -> {
            String operatingRoomNo = new String(mqttMessage.getPayload());
            CallDeviceScreenVo screenVo = screenService.getByOperatingRoomNo(operatingRoomNo);

            //生成订单号
            String orderNo = generateOrderNo();
            Date now = new Date();

            //存到数据库
            CallTaskOrderEntity taskOrder = new CallTaskOrderEntity();
            taskOrder.setOrderNo(orderNo);
            taskOrder.setSourceDeviceCode(screenVo.getCode());
            taskOrder.setOperatingRoomNo(operatingRoomNo);
            taskOrder.setAddress(screenVo.getAddress());
            taskOrder.setCreateAt(now);
            taskOrder.setUpdateAt(now);
            taskOrder.setState(CallTaskOrderEntity.STATUS_TO_OBTAIN);
            taskOrder.setType(1);
            taskOrderService.save(taskOrder);
        });
    }

    private String generateOrderNo(){
        StringBuffer orderNoBuffer = new StringBuffer();
        orderNoBuffer.append(Constant.ORDER_NO_PREFIX);
        orderNoBuffer.append(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        RLock rLock = redisson.getLock(Constant.LOCK_GENERATE_ORDER_NO);
        try{
            //加锁
            if (rLock.tryLock(10,10, TimeUnit.SECONDS)){
                Long num = taskOrderService.countTaskOrder();
                orderNoBuffer.append(new DecimalFormat("0000").format(num + 1));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return orderNoBuffer.toString();
    }
}
